#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""诊断监控系统问题"""

import sys
import subprocess
import json

def check_api_service():
    """检查API服务状态"""
    print("=== 检查API服务 ===")
    try:
        import requests
        response = requests.get("http://localhost:5000/api/status", timeout=5)
        if response.status_code == 200:
            status = response.json()
            print(f"✓ API服务运行正常")
            print(f"  监控状态: {status.get('monitoring_status')}")
            print(f"  房间URL: {status.get('room_url', '未设置')}")
            return True
        else:
            print(f"✗ API服务响应异常: {response.status_code}")
            return False
    except Exception as e:
        print(f"✗ API服务未运行或无法访问: {e}")
        return False

def check_chrome_installation():
    """检查Chrome安装"""
    print("\n=== 检查Chrome安装 ===")
    chrome_paths = [
        "/usr/bin/chromium-browser",
        "/usr/bin/google-chrome",
        "/usr/bin/chrome"
    ]
    
    found = False
    for path in chrome_paths:
        try:
            result = subprocess.run([path, "--version"], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"✓ 找到Chrome: {path}")
                print(f"  版本: {result.stdout.strip()}")
                found = True
                break
        except:
            continue
    
    if not found:
        print("✗ 未找到Chrome浏览器")
    return found

def check_chromedriver():
    """检查ChromeDriver"""
    print("\n=== 检查ChromeDriver ===")
    driver_paths = [
        "/usr/bin/chromedriver",
        "/usr/local/bin/chromedriver",
        "/snap/bin/chromium.chromedriver",
        "/home/lc/.local/bin/chromedriver"
    ]
    
    found = False
    for path in driver_paths:
        try:
            result = subprocess.run([path, "--version"], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"✓ 找到ChromeDriver: {path}")
                print(f"  版本: {result.stdout.strip()}")
                found = True
                break
        except:
            continue
    
    if not found:
        print("✗ 未找到ChromeDriver")
        print("  建议运行: pip install webdriver-manager")
    return found

def check_selenium_import():
    """检查Selenium模块"""
    print("\n=== 检查Selenium模块 ===")
    try:
        import selenium
        from selenium import webdriver
        print(f"✓ Selenium已安装: {selenium.__version__}")
        return True
    except ImportError as e:
        print(f"✗ Selenium未安装: {e}")
        print("  建议运行: pip install selenium")
        return False

def test_selenium_connection():
    """测试Selenium连接"""
    print("\n=== 测试Selenium连接 ===")
    try:
        from selenium import webdriver
        from selenium.webdriver.chrome.options import Options
        
        options = Options()
        options.add_argument("--headless")
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-dev-shm-usage")
        
        # 尝试使用webdriver-manager
        try:
            from webdriver_manager.chrome import ChromeDriverManager
            driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
            print("✓ 使用webdriver-manager成功创建Chrome驱动")
        except:
            # 尝试默认路径
            driver = webdriver.Chrome(options=options)
            print("✓ 使用默认路径成功创建Chrome驱动")
        
        driver.quit()
        return True
    except Exception as e:
        print(f"✗ 无法创建Chrome驱动: {e}")
        return False

def check_room_config():
    """检查房间配置"""
    print("\n=== 检查房间配置 ===")
    try:
        with open("config.json", "r") as f:
            config = json.load(f)
        room_url = config.get("room_url", "")
        if room_url:
            print(f"✓ 已配置房间URL: {room_url}")
        else:
            print("✗ 未配置房间URL")
        return bool(room_url)
    except Exception as e:
        print(f"✗ 无法读取配置文件: {e}")
        return False

def start_monitoring_test():
    """尝试启动监控"""
    print("\n=== 尝试启动监控 ===")
    try:
        import requests
        # 先检查是否已在监控
        status = requests.get("http://localhost:5000/api/status", timeout=5).json()
        if status.get("monitoring_status") == "monitoring":
            print("! 监控已在运行中")
            return True
        
        # 尝试启动监控
        response = requests.post("http://localhost:5000/api/start", timeout=10)
        if response.status_code == 200:
            print("✓ 成功发送启动监控请求")
            result = response.json()
            print(f"  响应: {result.get('message')}")
            return True
        else:
            print(f"✗ 启动监控失败: {response.status_code}")
            print(f"  响应: {response.text}")
            return False
    except Exception as e:
        print(f"✗ 无法启动监控: {e}")
        return False

def main():
    print("抖音直播监控诊断工具")
    print("=" * 50)
    
    # 执行各项检查
    api_ok = check_api_service()
    chrome_ok = check_chrome_installation()
    driver_ok = check_chromedriver()
    selenium_ok = check_selenium_import()
    
    if selenium_ok and chrome_ok:
        selenium_test_ok = test_selenium_connection()
    else:
        selenium_test_ok = False
        print("\n跳过Selenium连接测试（依赖项未满足）")
    
    room_ok = check_room_config()
    
    # 如果API服务运行正常，尝试启动监控
    if api_ok and room_ok:
        monitor_ok = start_monitoring_test()
    else:
        monitor_ok = False
        print("\n跳过监控启动测试（前置条件未满足）")
    
    # 总结
    print("\n" + "=" * 50)
    print("诊断总结:")
    if all([api_ok, chrome_ok, driver_ok, selenium_ok, selenium_test_ok, room_ok]):
        print("✓ 所有检查通过！系统应该可以正常工作。")
        if not monitor_ok:
            print("  但监控启动失败，请检查日志文件 live_monitor.log")
    else:
        print("✗ 发现以下问题:")
        if not api_ok:
            print("  - API服务未运行，请先运行: python3 app.py")
        if not chrome_ok:
            print("  - Chrome未安装，请安装: sudo apt install chromium-browser")
        if not driver_ok:
            print("  - ChromeDriver未找到，将使用webdriver-manager自动下载")
        if not selenium_ok:
            print("  - Selenium未安装，请运行: pip install selenium webdriver-manager")
        if not selenium_test_ok and selenium_ok and chrome_ok:
            print("  - Selenium无法连接Chrome，请检查版本兼容性")
        if not room_ok:
            print("  - 未配置房间URL，请通过API配置或编辑config.json")

if __name__ == "__main__":
    main()